<?php

namespace App\Module\Admin\Controllers;

use App\System\Base\Helpers\Traits\CommonController;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests, CommonController;
    /*
     * $invariant 不需要转成字符串格式的字段名
     */
    public function getExcel($fileName,$headArr,$data,$invariant=array()){
        $date = date("Y_m_d",time());
        $fileName .= "_{$date}.csv";
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$fileName.'"');
        header('Cache-Control: max-age=0');
        $fp = fopen('php://output','w');
        foreach($headArr as $i => $v){
            // CSV用Excel打开时，不支持UTF-8编码，而支持GBK编码，一定要转换，否则乱码
            $head[$i] = iconv('utf-8', 'gbk', $v);
        }
        // 将数据通过fputcsv写到文件句柄
        fputcsv($fp, $head);
        foreach ($data as $key=>$value)
        {
            foreach ($value as $k=> $vl){
                if($invariant){
                    if(!in_array($k,$invariant)){
                        $vl = $vl."\t";
                    }
                }else{
                    $vl = $vl."\t";
                }
                $row[$k] = iconv('utf-8', 'gbk//TRANSLIT', $vl);
            }
            fputcsv($fp, $row);
        }

        fclose($fp);
        return true;
    }
}
